package cvs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class CVSReport {

	public static void main(String[] args) {
		validCustomer();
		System.out.println("end");
	}

	private static void validCustomer() {
		String dir = "C:\\Documents and Settings\\Samsung.SAMSUNG-A8F\\My Documents\\";
		String fileName = "valid_customer";

		String SqlfileName = dir + fileName + ".sql";
		String outputName = dir + fileName;
		buildCVS(SqlfileName, outputName);
	}

	private static void tier2() {
		String dir = "C:\\Documents and Settings\\Samsung.SAMSUNG-A8F\\Desktop\\smi\\report requested\\territory\\Request for BTA Rev data\\";
		String fileName = "TeritoryReport-2Tier-2009-2010-source";

		String SqlfileName = dir + fileName + ".sql";
		String outputName = dir + fileName;
		buildCVS(SqlfileName, outputName);
	}

	public static void tier3() {
		String dir = "C:\\Documents and Settings\\Samsung.SAMSUNG-A8F\\Desktop\\smi\\report requested\\territory\\";
		String fileName = "TeritoryReport-3Tier-2009-2010_with national account_with territory with source";

		String SqlfileName = dir + fileName + ".sql";
		String outputName = dir + fileName;
		buildCVS(SqlfileName, outputName);
	}

	private static void buildCVS(String sqlfileName, String outputName) {
		System.out.println("outputName :" + outputName);
		PreparedStatement ps;
		ResultSet rs;

		String sql = readText(sqlfileName);

		System.out.println(sql);
		DBConnectorReal connector = new DBConnectorReal();
		try {
			connector.start();
			Connection connection = connector.getConnection();

			ps = connection.prepareStatement(sql);
			rs = ps.executeQuery();

			CSVGenerator generator = new CSVGenerator(new File(outputName
					+ ".csv"));
			generator.build(rs);
			generator.close();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			connector.close();
		}
		System.out.println("end");
	}

	public static String readText(String fileNamw) {
		StringBuffer sb = new StringBuffer();
		try {
			BufferedReader in = new BufferedReader(new FileReader(fileNamw));
			String str;
			while ((str = in.readLine()) != null) {
				sb.append(str);
				sb.append("\n");
			}
			in.close();
		} catch (IOException e) {
		}

		return sb.toString();
	}
}
